package com.dream.xiaobo.controller;

import com.dream.xiaobo.entity.Orders;
import com.dream.xiaobo.entity.Product;
import com.dream.xiaobo.entity.Type;
import com.dream.xiaobo.entity.User;
import com.dream.xiaobo.service.*;
import com.dream.xiaobo.service.impl.*;
import com.dream.xiaobo.utils.Constants;
import com.google.gson.Gson;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.InvocationTargetException;
import java.math.BigDecimal;
import java.sql.SQLException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @author xiaobo
 * @date 2021/9/4 - 13:02
 */
@WebServlet("/admin")
public class AdminController extends BaseServlet {

    /**
     * 依次创创建实例化对象
     */
    private AdminService adminService = new AdminServiceImpl();

    private TypeService typeService = new TypeServiceImpl();

    private UserService userService = new UserServiceImpl();

    private OrdersService ordersService = new OrdersServiceImpl();

    private ProductService productService = new ProductServiceImpl();

    /**
     * 登录模块
     * @param request
     * @param response
     * @return
     * @throws InvocationTargetException
     * @throws IllegalAccessException
     * @throws SQLException
     */
    public String login(HttpServletRequest request, HttpServletResponse response) throws InvocationTargetException, IllegalAccessException, SQLException {

        //获取输入的用户名
        String username = request.getParameter("username");

        //获取输入的密码
        String password = request.getParameter("password");

        //调用管理员登录业务逻辑方法
        User admin = adminService.selectAdminByName(username,password);

        //将信息存放到Session中返回到前端
        request.getSession().setAttribute("admin",admin);

        //返回管理员界面
        return Constants.FOR_WARD + "/admin/admin.jsp";
    }

    /**
     * 商品分类显示模块
     * @param request
     * @param response
     * @return
     * @throws SQLException
     */
    public String typeShow(HttpServletRequest request,HttpServletResponse response) throws SQLException {

        //调用商品分类业务逻辑方法
        List<Type> list = typeService.findAll();

        //将信息存放到Session中
        request.getSession().setAttribute("goodsTypeList",list);

        //返回商品分类显示页面
        return Constants.FOR_WARD + "/admin/showGoodsType.jsp";
    }

    /**
     * 商品显示模块
     * @param request
     * @param response
     * @return
     * @throws SQLException
     * @throws InvocationTargetException
     * @throws IllegalAccessException
     */
    public String productShow(HttpServletRequest request,HttpServletResponse response) throws SQLException, InvocationTargetException, IllegalAccessException {

        //调用商品业务逻辑方法
        List<Product> list = productService.findProduct();

        //将查询到的信息存放到Session中返回回去
        request.getSession().setAttribute("goodsList",list);

        //返回商品显示页面
        return Constants.FOR_WARD + "/admin/showGoods.jsp";
    }

    /**
     * 添加商品分类模块
     * @param request
     * @param response
     * @return
     * @throws InvocationTargetException
     * @throws IllegalAccessException
     * @throws SQLException
     */
    public String addType(HttpServletRequest request,HttpServletResponse response) throws InvocationTargetException, IllegalAccessException, SQLException {

        //获取到分类名字
        String typename = request.getParameter("typename");
        //获取到分类描述
        String typeinfo = request.getParameter("typeinfo");

        //创建商品分类实例化对象
        Type type = new Type();
        //赋值
        type.settName(typename);
        type.settInfo(typeinfo);

        //调用商品分类业务逻辑方法
        typeService.insertType(type);

        //返回商品分类显示页面
        return Constants.FOR_WARD + "/admin?method=typeShow";
    }

    /**
     * 添加商品模块
     * @param request
     * @param response
     * @return
     * @throws SQLException
     * @throws InvocationTargetException
     * @throws IllegalAccessException
     * @throws ParseException
     */
    public String addProduct(HttpServletRequest request,HttpServletResponse response) throws SQLException, InvocationTargetException, IllegalAccessException, ParseException {

        try {
            //创建商品实例化对象
            Product product = new Product();
            //创建插件实例化对象
            DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
            //创建插件实例化对象
            ServletFileUpload fileUpload = new ServletFileUpload(diskFileItemFactory);
            //获取请求中数据
            List<FileItem> fileItems = fileUpload.parseRequest(request);
            //遍历接收到的数据内容
            for(FileItem fileItem: fileItems){
                //拿到input框中的值
                String name = fileItem.getName();
                //判断
                if(fileItem.isFormField()){
                    //拿到input框中name名字
                    String fieldName = fileItem.getFieldName();
                    //判断input框中的名字一次进行赋值
                    switch (fieldName){
                        case "pName":
                            String pName = fileItem.getString("UTF-8");
                            product.setpName(pName);
                            break;
                        case "pPrice":
                            String pPrice =  fileItem.getString();
                            BigDecimal bigPrice = new BigDecimal(pPrice);
                            product.setpPrice(bigPrice);
                            break;
                        case "pTime":
                            String pTime = fileItem.getString("UTF-8");
                            DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
                            Date date = dateFormat.parse(pTime);
                            product.setpTime(date);
                            break;
                        case "pState":
                            String pState = fileItem.getString("UTF-8");
                            product.setpState(Integer.parseInt(pState));
                            break;
                        case "pINfo":
                            String pInfo = fileItem.getString("UTF-8");
                            product.setpInfo(pInfo);
                            break;
                        case "tId":
                            String tId = fileItem.getString("UTF-8");
                            product.settId(Integer.parseInt(tId));
                            break;
                    }
                }else{
                    //拿到流
                    InputStream inputStream = fileItem.getInputStream();
                    //获取上传路径
                    String path = request.getServletContext().getRealPath("image/" + name);
                    System.out.println(path);
                    //创建输出流实例化对象
                    OutputStream outputStream = new FileOutputStream(path);
                    int temp = 0;
                    //遍历、如果为-1、则停止输出
                    while((temp = inputStream.read()) != -1) {
//                        System.out.println(temp);
                        outputStream.write(temp);
                    }
                    /**
                     * 关闭资源
                     */
                    outputStream.close();
                    inputStream.close();
                    System.out.println("上传成功");
                    //添加到对象当中
                    product.setpImage("image/" + name);
                }
            }
            //调用商品业务逻辑
            productService.insertProduct(product);
        } catch (FileUploadException | IOException e) {
            e.printStackTrace();
        }

        //返回商品显示页面
        return Constants.FOR_WARD + "/admin?method=productShow";
    }

    /**
     * 管理员管理模块
     * @param request
     * @param response
     * @throws SQLException
     * @throws InvocationTargetException
     * @throws IllegalAccessException
     */
    public void adminManagement(HttpServletRequest request,HttpServletResponse response) throws SQLException, InvocationTargetException, IllegalAccessException {

        //调用商品分类业务逻辑方法
        List<Type> goodsTypeList = typeService.findAll();
        //将查询到的结果存放到Session中传到前端
        request.getSession().setAttribute("goodsTypeList",goodsTypeList);
        //调用商品业务逻辑方法
        List<Product> goodsList = productService.findProduct();
        //将查询到的结果存放到Session中传到前端
        request.getSession().setAttribute("goodsList",goodsList);
    }

    /**
     * 注销登录
     * @param request
     * @param response
     * @return
     */
    public String logout(HttpServletRequest request,HttpServletResponse response){

        //销毁Session
        request.getSession().invalidate();

        //返回登录页面
        return Constants.FOR_WARD + "/admin/login.jsp";
    }

    /**
     * 会员用户模块
     * @param request
     * @param response
     * @return
     * @throws SQLException
     */
    public String member(HttpServletRequest request,HttpServletResponse response) throws SQLException {

        //调用用户业务逻辑方法
        List<User> list = userService.checkRoleUser();
        //创建Gson实例化对象
        Gson gson = new Gson();
        //将查询到的结果转换为json格式
        String json = gson.toJson(list);
        //返回转换后的JSON数据
        return json;
    }

    /**
     * 非会员用户模块
     * @param request
     * @param response
     * @return
     * @throws SQLException
     */
    public String NOTMember(HttpServletRequest request,HttpServletResponse response) throws SQLException {

        //调用用户业务逻辑方法
        List<User> list = userService.checkStatusUser();
        //创建Gson实例化对象
        Gson gson = new Gson();
        //将查询到的结果转换为json格式
        String json = gson.toJson(list);
        //返回转换后的JSON数据
        return json;
    }

    /**
     * 删除用户
     * @param request
     * @param response
     * @throws SQLException
     */
    public void deleteUser(HttpServletRequest request,HttpServletResponse response) throws SQLException {

        //获取用户Id
        String uId = request.getParameter("uid");
        //调用用户业务逻辑方法
        userService.deleteUser(uId);
    }

    /**
     * 显示订单模块
     * @param request
     * @param response
     * @return
     * @throws SQLException
     * @throws InvocationTargetException
     * @throws IllegalAccessException
     */
    public String orderShow(HttpServletRequest request,HttpServletResponse response) throws SQLException, InvocationTargetException, IllegalAccessException {

        //调用订单业务逻辑方法
        List<Orders> list = ordersService.findOrder();
        //将查询到的信息返回到前端
        request.setAttribute("orderList",list);
        //返回订单显示页面
        return Constants.FOR_WARD + "/admin/showAllOrder.jsp";
    }

    /**
     * 更新订单模块
     * @param request
     * @param response
     * @return
     * @throws SQLException
     */
    public String updataOrder(HttpServletRequest request,HttpServletResponse response) throws SQLException {

        //获取到订单Id
        String oId = request.getParameter("oid");
        //调用订单业务逻辑
        ordersService.updateOrderByOIdHair(oId);
        //返回订单显示页面
        return Constants.FOR_WARD + "/admin?method=orderShow";
    }
}
